package com.study.leetcode;

import java.util.Arrays;

public class Solution_105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length < 1) return null;
        TreeNode treeNode = new TreeNode(preorder[0]);
        int index = findIndex(inorder, preorder[0]);
        int[] pre_left = Arrays.copyOfRange(preorder, 1, index + 1);
        int[] pre_right = Arrays.copyOfRange(preorder, index + 1, preorder.length);
        int[] in_left = Arrays.copyOfRange(inorder, 0, index);
        int[] in_right = Arrays.copyOfRange(inorder, index + 1, inorder.length);
        treeNode.left = buildTree(pre_left, in_left);
        treeNode.right = buildTree(pre_right, in_right);
        return treeNode;
    }

    public static int findIndex(int[] inorder, int num) {
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == num) {
                return i;
            }
        }
        return 0;
    }
}
